package com.leejxx.health.config;

import com.leejxx.health.security.service.SecurityUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * @Author LeeJx
 * @ClassName WebSecurityConfig
 * @Description TODO
 * @date 2021/1/9 12:17
 * @Version 1.0
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private SecurityUserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        //用户详情创建一个配置类
//        InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder> configurer = auth.inMemoryAuthentication();
//        // 配置三个用户
//        // 密码格式：{算法}密文      noop表示不加密,示例中的MD5值对应的原始密码是1234
//        // authorities用于提供用户的角色和权限，默认带ROLE_前缀的是角色，否则是权限
//        configurer.withUser("admin").password("{noop}1234").authorities("ROLE_ADMIN");
//        configurer.withUser("zhangSan").password("{noop}1234").authorities("ROLE_01", "add");
//        configurer.withUser("liSi").password("{MD5}81dc9bdb52d04dc20036dbd8313ed055").authorities("ROLE_02", "find");

        // 设置自定义的UserDetailService
        auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 指定访问控制规则
        // 1-通过authorizeRequests()开启一个拦截规则
        // 2-通过antMatchers()指定需要拦截的资源，参数为ant表达式
        // 3-通过access()指定访问该资源所需要的权限，参数为权限表达式
//        http.authorizeRequests().antMatchers("*.js", "*.css").access("permitAll()");
//        http.authorizeRequests().antMatchers("/pages/checkgroup.html").access("hasAnyAuthority('ROLE_ADMIN','add')");
//        http.authorizeRequests().antMatchers("/main.html", "/pages/**").access("isAuthenticated()");

        // 使用springSecurity默认的登录配置(自动生成登录页面、登录接口、退出接口……)
//        http.formLogin();

        // 关闭防CSRF攻击
        http.csrf().disable()
                // 设置登录相关配置
                .formLogin()
                .loginProcessingUrl("/sec/login") // 登录请求地址
                .failureForwardUrl("/user/loginFail") // 登录失败转地址
                .successForwardUrl("/user/loginSuccess") // 登录成功转发地址
                .loginPage("http://localhost:8080/pages/login.html") // 登录页地址
                // 设置登出相关配置
                .and().logout()
                .logoutUrl("/sec/logout") // 登出请求地址
                .logoutSuccessUrl("http://localhost:8080/pages/login.html"); // 登出成功后跳转地址
    }
}
